package admin

import (
	"mycms/global"
	"mycms/model/system"
	systemReq "mycms/model/system/request"
	systemRes "mycms/model/system/response"
	"mycms/service/common"
	"strings"
)

//	API管理列表
func GetApisList(param systemReq.SearchApiParams) (err error, list interface{}, total int64) {
	var apisList []system.Apis

	db := global.DB.Model(&system.Apis{})
	err = db.Count(&total).Error
	if err != nil {
		return err, apisList, total
	} else {
		if param.Path != "" {
			db = db.Where("path LIKE ?", "%"+param.Path+"%")
		}

		if param.Description != "" {
			db = db.Where("description LIKE ?", "%"+param.Description+"%")
		}


		if param.ApiGroup != "" {
			db = db.Where("api_group = ?", param.ApiGroup)
		}

		//	查询
		err = db.Scopes(common.Paginate(param.PageInfo)).Order("api_group").Find(&apisList).Error
	}
	return err, apisList, total
}


//	API现有分组
func GetApisGroupList() (err error, list interface{}) {

	var groupList []systemRes.Group
	err = global.DB.Model(&system.Apis{}).Group("api_group").Select("api_group").Find(&groupList).Error

	return err, groupList
}

//	创建API
func CreateApis(param systemReq.CreateApiParams) (err error) {

	apis := &system.Apis{
		Path: "/admin/v1/"+strings.TrimSpace(param.Path),
		Method: param.Method,
		ApiGroup: param.ApiGroup,
		Description: param.Description,
	}

	err = global.DB.Create(&apis).Error

	return err
}

//	更新API
func UpdateApis(param systemReq.UpdateApiParams) (err error) {

	var apis system.Apis
	err = global.DB.Where("id = ?", param.Id).First(&apis).Error

	if err == nil{
		param.Path = strings.TrimSpace(param.Path)
		err = global.DB.Model(apis).Select("*").Updates(&param).Error
	}

	return err
}

//	API详情
func GetApisInfo(param systemReq.ApisInfoParams) (err error, apis system.Apis) {
	err = global.DB.Where("id = ?", param.Id).First(&apis).Error

	return err, apis
}

// 删除API
func DelApis(param systemReq.DelApisParams) (err error) {
	var apis system.Apis
	err = global.DB.Where("id = ?", param.Id).Delete(&apis).Error
	return err
}

//	所有API列表
func GetAllApisList() (err error, list interface{}) {
	var apisList []system.Apis


	db := global.DB.Model(&system.Apis{})
	//	查询
	err = db.Select("id, path, method, api_group, description").Order("api_group").Find(&apisList).Error

	_, groups := GetApisGroupList()

	//	TODO 组装分组数据
	var allApis []systemRes.AllAlisResponse
	for _, val := range groups.([]systemRes.Group){

		var apiparam []systemRes.ApiParam
		for _,v:= range apisList {
			if v.ApiGroup == val.ApiGroup{
				apiparam = append(apiparam, systemRes.ApiParam{
					ID: v.ID,
					Path: v.Path,
					Method: v.Method,
					ApiGroup: v.ApiGroup,
					Description: v.Description+"（"+v.Method+" | "+v.Path+"）",
				})
			}
		}

		allApis = append(allApis, systemRes.AllAlisResponse{
			ApiGroup: val.ApiGroup,
			Options: apiparam,
		})
	}

	return err, allApis
}

